﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AIS.SDK.Api;
using AIS.SDK.Api.ApiResponses;
using AIS.SDK.Api.Requests;
using AIS.SDK.Api.Response;
using AIS.SDK.Handler;
using AIS.SDK.Logger;
using AIS.SDK.Model;
using Common;

namespace AIS.SDK.Handler
{
    /// <summary>
    /// 认证类
    /// </summary>
    [HandlerContract]
    public class AISClientHandler
    {

 

        private static DateTime GetAccessToken_Time;
        /// <summary>
        /// 过期时间为7200秒
        /// </summary>
        private static int Expires_Period = 7200;


        #region 公用方法
        /// <summary>
        /// 验证，返回access_token
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="appsecret"></param>
        /// <returns></returns>
        [MethodOperation]
        public AccessTokenResponse Tokenrequest(string username, string password,string devicename,string role,string environment)
        {
            var appidca = new AppIdentication(username,password,devicename,role,environment);
            var request = new TokenrequestV2(appidca);
            IApiClient client = new DefaultApiClient();
            var response = client.Execute(request);
            if (response.ok )
            {
                //成功验证
                AISClientHandler.Instance.DeviceName = devicename;
                AISClientHandler.Instance.Token = response.GetDataObject<AccessTokenResponse>().token;  //Common.JsonHelper.JsonToObject<AccessTokenResponse>(response.data.ToString()).token;
                //AISClientHandler.Instance.Token = response.GetObject().;
                AISClientHandler.Instance.UserName = username;
                AISClientHandler.Instance.Password = password;
                AISClientHandler.Instance.Environment = environment;
                AISClientHandler.Instance.Role = role;
                AISClientHandler.Instance.simpleDateFormat = response.GetDataObject<AccessTokenResponse>().simpleDateFormat;


                return response;
            }
            else
            {
                GetAccessToken_Time = DateTime.MinValue;
                if (response.ErrorMessage.Contains("Authorization Failure"))
                    response.ErrorMessage = "验证失败，请检查用户名密码是否正确，或者密码已过期，请及时登陆JDE进行修改";
                throw new MQException("401", response.ErrorMessage);
            }
        }
        [MethodOperation]
        public bool ValidateToken(string token)
        {
            try
            {
                var appidca = new AppIdentication(token);
                var request = new ValidateTokenV2(appidca);
                IApiClient client = new DefaultApiClient();
                var response = client.Execute(request);
                if (response.ok )
                {
                    //成功验证
                    return true;
                }
                else
                {
                    throw new Exception(response.ErrorMessage);
                }
            }
            catch (Exception x)
            {
                Logger.Log4Net.Error(x.Message);
                return false;
            }
        }

        /// <summary>
        /// 获取当前的登录凭证
        /// </summary>
        /// <returns></returns>
        [MethodOperation]
        public string  GetCurrentToken()
        {
            //如果为空，或者过期，需要重新获取
            if (string.IsNullOrEmpty(AISClientHandler.Instance.Token) || HasExpired())
            {
                //获取
                 //OAuth(CurrentUser.Instance.AppID, CurrentUser.Instance.Appsecret);
            }
            string str= AISClientHandler.Instance.Token;
            //后期再开发出重新登录
            return str;
        }

        


        public string GetCurrentDevicename()
        {
            //如果为空，或者过期，需要重新获取
            if (string.IsNullOrEmpty(AISClientHandler.Instance.DeviceName)  )
            {
                //获取
                //OAuth(CurrentUser.Instance.AppID, CurrentUser.Instance.Appsecret);
            }
            string str = AISClientHandler.Instance.DeviceName;
            //后期再开发出重新登录
            return str;
        }

        #region 数据查询
        public FormserviceResponse OrderQuery(string ordernumber, string ordertype, string formname, UserInfo user)
        {
            var qry = new Query()
            {
                autoClear = true,
                matchType = "MATCH_ALL",
                autoFind = true,
                condition = new List<condition>(new condition[] {
                     new condition() { controlId="9", Operator="EQUAL" ,
                         Value = new List<Value>(new Value[] {
                                new Value(){ content=ordernumber, specialValueId="LITERAL" }
                                }
                        )
                     },
                      new condition() { controlId="13", Operator="EQUAL" ,
                         Value = new List<Value>(new Value[] {
                                new Value(){ content=ordertype, specialValueId="LITERAL" }
                                }
                        )
                     }
                 })
            };
            var frequest = new FormRequest()
            {
                formName = formname,
                version= "MBR001A",
                query = qry,
                outputType = "VERSION2",
                formServiceAction = "R",
                bypassFormServiceEREvent = true,
                returnControlIDs = "1[45,46,48,49,306,55,51]",
                environment="JPY920"

            };

            var request = new FormserviceV2(frequest,user.token,user.devicename);
            IApiClient client = new DefaultApiClient();
            var response = client.Execute(request);
            if (response.ErrorCode == 0)
            {
                //成功验证
                return response;
            }
            else
            {

                throw new Exception(response.ErrorMessage);
            }
        }
        /// <summary>
        /// 根据窗体版本查询订单
        /// </summary>
        /// <param name="ordernumber"></param>
        /// <param name="ordertype"></param>
        /// <param name="formname"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public FormserviceResponse OrderQuery(string formname,string version,QueryConditionCollection _conditions)
        {

            if (string.IsNullOrWhiteSpace(GetCurrentToken()))
                throw new AISApiException(444, "Token不能为空");


            List<condition> cons = new List<condition>();
            foreach (condition fc in _conditions)
            {
                cons.Add(new condition() {
                     controlId=fc.controlId,
                     Operator=fc.Operator,
                      Value=fc.Value
                });
            }

            var qry = new Query()
            {
                autoClear = true,
                matchType = "MATCH_ALL",
                autoFind = true,
                condition=cons
            };
            var frequest = new FormRequest()
            {
                formName = formname,
                version = version,
                query = qry,
                outputType = "VERSION2",
                formServiceAction = "R",
                bypassFormServiceEREvent = true,
                returnControlIDs = "1[45,46,48,49,306,55,51]",
                environment = "JPY920"

            };
            //DeviceName 需要为空
            var request = new FormserviceV2(frequest, GetCurrentToken(),"");
            IApiClient client = new DefaultApiClient();
            var response = client.Execute(request);
            if (response.ErrorCode == 0)
            {
                //成功验证
                return response;
            }
            else
            {

                throw new Exception(response.ErrorMessage);
            }
        }

        public FormserviceResponse OrderQuery(string formname, string version, string _strconditions)
        {
            return OrderQuery(formname,version,new QueryConditionCollection().FromJson(_strconditions));
        }


        public FormserviceResponse OrderQuery(string formname, string version, FormActionsCollection _actions)
        {

            if (string.IsNullOrWhiteSpace(GetCurrentToken()))
                throw new AISApiException(444, "Token不能为空");


            List<FSREvent> actions = new List<FSREvent>();
            foreach (FSREvent fc in _actions)
            {
                actions.Add(new FSREvent()
                {
                    command = fc.command,
                    controlID = fc.controlID,
                    value = fc.value,
                    gridAction = fc.gridAction
                });
            }
            var frequest = new FormRequest()
            {
                formName = formname,
                version = version,
                outputType = "VERSION2",
                //maxPageSize = "2",
                formServiceAction = "R",
                bypassFormServiceEREvent = true,
                environment = "JPY920",
                formActions = actions,
                stopOnWarning = "True"
            };
            //DeviceName 需要为空
            var request = new FormserviceV2(frequest, GetCurrentToken(), "");
            IApiClient client = new DefaultApiClient();
            var response = client.Execute(request);
            if (response.ErrorCode == 0)
            {
                //成功验证
                return response;
            }
            else
            {

                throw new Exception(response.ErrorMessage);
            }



        }
        #endregion


        #region 数据新增

        public FormserviceResponse FormserviceV2(string token, FormRequest formRequest)
        {
            if (!ValidateToken(token))
                throw new Exception("无效的Token");

            Logger.Log4Net.Debug($"Token:{token}");
            var request = new FormserviceV2(formRequest, token, "");
            IApiClient client = new DefaultApiClient();
            var response = client.Execute(request);
            if (response.ok )
            {
                //成功验证
                //return response;
                return response.GetDataObject<FormserviceResponse>();
            }
            else
            {

                throw new Exception(response.ErrorMessage);
            }
        }
        public FormserviceResponse Formservice_insert(string formname, string version, FormActionsCollection _actions)
        {

            if (string.IsNullOrWhiteSpace(GetCurrentToken()))
                throw new AISApiException(444, "Token不能为空");


            List<FSREvent> actions = new List<FSREvent>();
            foreach (FSREvent fc in _actions)
            {
                actions.Add(new FSREvent()
                {
                      command=fc.command,
                      controlID=fc.controlID,
                      value=fc.value,
                      gridAction=fc.gridAction
                });
            }
            var frequest = new FormRequest()
            {
                formName = formname,
                version = version,
                outputType = "VERSION2",
                stopOnWarning="True" ,
                maxPageSize = "1",
                formServiceAction = "C",
                bypassFormServiceEREvent = true,
                environment = "JPY920",
                formActions= actions
                
                
            };
            //DeviceName 需要为空
            var request = new FormserviceV2(frequest, GetCurrentToken(), "");
            IApiClient client = new DefaultApiClient();
            var response = client.Execute(request);
            if (response.ok)
            {
                //成功验证
                return response.GetDataObject<FormserviceResponse>(); ;
            }
            else
            {

                throw new Exception(response.ErrorMessage);
            }



        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="formname"></param>
        /// <param name="version"></param>
        /// <param name="_headers"></param>
        /// <param name="_bodys">行列数据类型</param>
        /// <returns></returns>
        public FormserviceResponse Formservice_insert(string formname, string version , 
                                              FormActionsCollection _headers, 
                                              List<gridcolumnCollection> _bodys,
                                              FormActionsCollection _baraction)
        {
            FormActionsCollection fs = new FormActionsCollection();
            foreach (var dic in _headers)
            {
                fs.Add(new FSREvent()
                {
                    command = dic.command,
                    controlID = dic.controlID,
                    value = dic.value 
                     
                });
            }

            if (_bodys != null && _bodys.Count > 0)
            {
                List<gridrowInsertevents> gridrows = new List<gridrowInsertevents>();
                List<gridcolumnevent> gridcols = new List<gridcolumnevent>();
                //Foreach Rows
                foreach (var row in _bodys)
                {
                    gridcols = new List<gridcolumnevent>();
                    foreach (var col in  row)
                    {
                        gridcols.Add(new gridcolumnevent()
                        {
                            columnID = col.columnID,
                            command = col.command,
                            value = col.value
                        });
                    }
                    
                   gridrows.Add( new gridrowInsertevents() {  gridColumnEvents =gridcols});
                }

                //Add GirdID
                GridAction gridAction = new GridAction();
                gridAction.gridID = "1";
                gridAction.gridRowInsertEvents = gridrows;

                fs.Add(new FSREvent() { command= "SelectRow", gridAction=gridAction});
            }


            //fs.Add(new FSREvent() {  command= "DoAction",controlID= actionid });

            foreach (var dic in _baraction)
            {
                fs.Add(new FSREvent()
                {
                    command = dic.command,
                    controlID = dic.controlID,
                    value = dic.value

                });
            }


            return Formservice_insert(formname,version,fs);
        }

        #endregion



        public FormserviceResponse Formservice_update(string formname, string version, FormActionsCollection _actions)
        {

            if (string.IsNullOrWhiteSpace(GetCurrentToken()))
                throw new AISApiException(444, "Token不能为空");


            List<FSREvent> actions = new List<FSREvent>();
            foreach (FSREvent fc in _actions)
            {
                actions.Add(new FSREvent()
                {
                    command = fc.command,
                    controlID = fc.controlID,
                    value = fc.value,
                    gridAction = fc.gridAction
                });
            }
            var frequest = new FormRequest()
            {
                formName = formname,
                version = version,
                //outputType = "XML",
                //stopOnWarning="True" ,
                maxPageSize = "1",
                formServiceAction = "U",
                bypassFormServiceEREvent = true,
                environment = "JPY920",
                formActions = actions


            };
            //DeviceName 需要为空
            var request = new FormserviceV2(frequest, GetCurrentToken(), "");
            IApiClient client = new DefaultApiClient();
            var response = client.Execute(request);
            if (response.ok )
            {
                //成功验证
                return response.GetDataObject<FormserviceResponse>(); ;
            }
            else
            {

                throw new Exception(response.ErrorMessage);
            }



        }

        public FormserviceResponse Formservice_update(string formname, string version,
                                             FormActionsCollection _headers,
                                             List<gridcolumnCollection> _bodys,
                                             FormActionsCollection _baraction)
        {
            FormActionsCollection fs = new FormActionsCollection();
            foreach (var dic in _headers)
            {
                fs.Add(new FSREvent()
                {
                    command = dic.command,
                    controlID = dic.controlID,
                    value = dic.value

                });
            }

            if (_bodys != null && _bodys.Count > 0)
            {
                List<gridrowupdateevents> gridrows = new List<gridrowupdateevents>();
                List<gridcolumnevent> gridcols = new List<gridcolumnevent>();
                //Foreach Rows
                foreach (var row in _bodys)
                {
                    gridcols = new List<gridcolumnevent>();
                    foreach (var col in row)
                    {
                        gridcols.Add(new gridcolumnevent()
                        {
                            columnID = col.columnID,
                            command = col.command,
                            value = col.value
                        });
                    }
                    //此处rownumber 有隐患
                    gridrows.Add(new gridrowupdateevents() { gridColumnEvents = gridcols, rowNumber=0});
                }

                //Add GirdID
                GridAction gridAction = new GridAction();
                gridAction.gridID = "1";
                gridAction.gridRowUpdateEvents = gridrows;

                fs.Add(new FSREvent() { gridAction = gridAction });
            }


            //fs.Add(new FSREvent() {  command= "DoAction",controlID= actionid });

            foreach (var dic in _baraction)
            {
                fs.Add(new FSREvent()
                {
                    command = dic.command,
                    controlID = dic.controlID,
                    value = dic.value

                });
            }


            return Formservice_update(formname, version, fs);
        }

        #endregion



        #region  多窗体操作
        [MethodOperation]
        public AppstackResponse Appstack_execute(string token ,ApplicationStackRequest asrequest)
        {

            if (!ValidateToken(token))
                throw new Exception("无效的Token");

            Logger.Log4Net.Debug($"Token:{token}");
            var request = new AppstackV2(asrequest, token, "");
            IApiClient client = new DefaultApiClient();
            var response = client.Execute(request);
            if (response.ok)
            {
                //成功验证
                return response.GetDataObject<AppstackResponse>();
            }
            else
            {

                throw new Exception(response.ErrorMessage);
            }
        }

        #endregion


        #region 执行报表
        [MethodOperation]
        public ReportserviceResponse ReportService_execute(string token, LaunchUBERequest asrequest)
        {

            if (!ValidateToken(token))
                throw new Exception("无效的Token");

            Logger.Log4Net.Debug($"Token:{token}");
            var request = new ReportServiceV2(asrequest, token, "");
            IApiClient client = new DefaultApiClient();
            var response = client.Execute(request);
            if (response.ok)
            {
                //成功验证
                return response.GetDataObject<ReportserviceResponse>();
            }
            else
            {
                throw new Exception(response.message);
            }
        }
        #endregion
        /// <summary>
        /// 判断Access_token是否过期
        /// </summary>
        /// <returns>bool</returns>
        private bool HasExpired()
        {
            if (GetAccessToken_Time != null)
            {
                //过期时间，允许有一定的误差，一分钟。获取时间消耗
                if (DateTime.Now > GetAccessToken_Time.AddSeconds(Expires_Period).AddSeconds(-60))
                {
                    return true;
                }
            }
            return false;
        }


        # region 私有

        #region Instance
        private static AISClientHandler m_Instnace;

        public static AISClientHandler Instance
        {
            get
            {
                if (m_Instnace == null)
                {
                    m_Instnace = new AISClientHandler();
                }

                return m_Instnace;
            }
        }

        public AISClientHandler()
        {
        }
        #endregion
        //AppID
        private static string _username = "";
        public string UserName { get { return _username; } set { _username = value; } }
        //Endpoint
        private static string _password = "";
        public string Password { get { return _password; } set { _password = value; } }

        private static string _environment = "";
        public string Environment { get { return _environment; } set { _environment = value; } }

        private static string _devicename = "";
        public string DeviceName { get { return _devicename; } set { _devicename = value; } }


        //Endpoint
        private static string _token = "";
        public string Token { get { return _token; } set { _token = value; } }

        public string Role { get; set; }


        public string simpleDateFormat { get; set; }
        #endregion
    }
}
